package com.dragon.modules.yuegou.service.impl.merchant;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.exception.DragonException;
import com.dragon.common.web.PageRequest;
import com.dragon.modules.yuegou.entity.merchant.UserEntity;
import com.dragon.modules.yuegou.enums.OwnerType;
import com.dragon.modules.yuegou.enums.code.BusinessCode;
import com.dragon.modules.yuegou.enums.code.MerchantCode;
import com.dragon.modules.yuegou.enums.code.SystemCode;
import com.dragon.modules.yuegou.enums.merchant.UserMerchantType;
import com.dragon.modules.yuegou.mapper.merchant.UserMapper;
import com.dragon.modules.yuegou.model.merchant.User;
import com.dragon.modules.yuegou.model.system.WxOpenidRef;
import com.dragon.modules.yuegou.model.wallet.MerchantWallet;
import com.dragon.modules.yuegou.query.merchant.UserQuery;
import com.dragon.modules.yuegou.query.wallet.MerchantWalletQuery;
import com.dragon.modules.yuegou.service.merchant.UserService;
import com.dragon.modules.yuegou.service.system.WxOpenidRefService;
import com.dragon.modules.yuegou.service.wallet.MerchantWalletService;
import com.dragon.modules.yuegou.utils.PageToResultUtils;
import com.dragon.modules.yuegou.web.Check;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;

/**
 * 商户用户表 服务实现
 *
 * @author pbuilder generated
 * @date 2019-03-26 11:02:05
 * @version 2.0
 */
@Slf4j
@Service("merUserService")
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

	@Autowired
	private com.dragon.modules.yuegou.service.system.UserService sysUserService;

	@Autowired
	private MerchantWalletService merchantWalletService;

	@Autowired
	private WxOpenidRefService wxOpenidRefService;

	@Override
	@Transactional
	public void upgradeAccount(String merchantId, String merchantUserId) {
		UserQuery query = new UserQuery();
		query.merchantId().eq(merchantId);
		query.merchantType().eq(UserMerchantType.MERCHANT);
		// 将商户下的商户主账号变成员工账号
		list(query.toQueryWrapper()).forEach(user -> {
			user.setMerchantType(UserMerchantType.EMPLOYEE);
			updateById(user);
		});

		// 升级子账号为主账号
		User newUser = new User();
		newUser.setId(merchantUserId);
		newUser.setMerchantType(UserMerchantType.MERCHANT);
		updateById(newUser);
	}

	@Override
	public List<User> merchantUserList(String merchantId) {
		UserQuery query = new UserQuery();
		query.merchantId().eq(merchantId);
		query.del().eq(false);
		QueryWrapper<UserEntity> queryWrapper = query.toQueryWrapper();
		queryWrapper.orderByAsc(UserEntity.COL_MERCHANT_TYPE);
		List<UserEntity> entities = list(queryWrapper);
		if (CollectionUtils.isNotEmpty(entities)) {
			List<User> merchantUserList = entities.stream().map(User::new).collect(Collectors.toList());
			merchantUserList.forEach(user -> {
				com.dragon.modules.yuegou.entity.system.UserEntity sysUser = sysUserService.getById(user.getUserId());
				user.setUsername(sysUser.getUsername());
				user.setNickname(sysUser.getNickName());
				user.setMobile(sysUser.getMobile());
			});
			return merchantUserList;
		}
		return new ArrayList<>();
	}

	@Override
	public Map<String, User> getByIds(Collection<String> ids) {
		if (ids.isEmpty()) {
			return Collections.emptyMap();
		}

		return listByIds(ids).stream().map(User::new).collect(Collectors.toMap(User::getId, UnaryOperator.identity()));
	}

	@Override
	public IPage<User> list(PageRequest page, UserQuery query) {
		QueryWrapper<UserEntity> queryWrapper = query.toQueryWrapper();
		queryWrapper.orderByAsc(UserEntity.COL_ID);

		IPage<UserEntity> entityIPage = page(PageToResultUtils.resultToPage(page), queryWrapper);
		IPage<User> pageUser = entityIPage.convert(User::new);

		List<User> userList = pageUser.getRecords();
		if (CollectionUtils.isNotEmpty(userList)) {
			for (User user : userList) {
				com.dragon.modules.yuegou.entity.system.UserEntity sysUser = sysUserService.getById(user.getUserId());
				user.setSysUser(new com.dragon.modules.yuegou.model.system.User(sysUser));
			}
		}
		pageUser.setRecords(userList);

		return pageUser;

	}

	@Override
	public void voiceCof(String merchantUserId,Integer voiceCof) {
		UserEntity user = getById(merchantUserId);
		user.setVoiceCof(voiceCof);
		log.debug("商户修改语音播报提示，商户UserId={}，状态值={}", merchantUserId, voiceCof);
		updateById(user);
	}

	@Override
	public boolean repwd(String oldPwd, String newPwd, String repeatPwd, String merchantUserId) {
		UserEntity merchantUser = getById(merchantUserId);
		if (merchantUser != null) {
			sysUserService.changePwd(merchantUserId, oldPwd, newPwd, OwnerType.MERCHANT);
		}
		return true;
	}

	@Override
	public boolean findPwd(String mobile, String newPwd) {
		Check.notNull(mobile, SystemCode.MOBILE_NOTNULL.getMessage());
		Check.notNull(newPwd, SystemCode.PASSWORD_NOTNULL.getMessage());
		com.dragon.modules.yuegou.model.system.User sysuser = sysUserService.getMerchantUserByMobile(mobile);
		if (sysuser == null) {
			throw new DragonException(MerchantCode.MERCHANT_NOT_EXIST);
		}
		sysUserService.changePwd(sysuser.getId(), newPwd, OwnerType.MERCHANT);
		return true;
	}

	@Override
	public boolean setWithdrawPwd(String merchantId, String firstPwd) {
		setWithdrawPassword(merchantId, null, firstPwd);
		return true;
	}

	@Override
	public boolean resetWithdrawPwd(String merchantId, String oldPwd, String newPwd, String repeatPwd) {
		if (!newPwd.equals(repeatPwd)) {
			throw new DragonException(BusinessCode.PASSWORDS_ARE_INCONSISTENT);
		}
		setWithdrawPassword(merchantId, oldPwd, newPwd);
		return true;
	}

	private void setWithdrawPassword(String merchantId, String oldPwd, String newPwd) {
		MerchantWalletQuery query = new MerchantWalletQuery();
		query.merchantId().eq(merchantId);
		MerchantWallet merchantWallet = merchantWalletService.loadByMerchant(merchantId);

		if (null == merchantWallet) {
			throw new DragonException(BusinessCode.MERCHANT_NO_WALLET);
		}

		if (null != oldPwd && !oldPwd.equals(merchantWallet.getWithdrawPassword())) {
			throw new DragonException(BusinessCode.PASSWORD_IS_INCORRECT);
		}
		merchantWallet.setWithdrawPassword(newPwd);
		merchantWalletService.updateById(merchantWallet);
	}

	@Override
	public User getUser(String merchantId, String busdId) {
		Check.notNull(merchantId, "商户id不能为空");
		UserQuery query = new UserQuery();
		query.setDel(false);
		query.setMerchantId(merchantId);
		query.setBusdId(busdId);
		query.setMerchantType(UserMerchantType.MERCHANT);
		List<UserEntity> list = list(query.toQueryWrapper());
		if (CollectionUtils.isNotEmpty(list)){
			return new User(list.get(0));
		}
		return new User();
	}

	@Override
	public void createMerchantUser(String merchantId, String username, String account, String busdId, String password,
			UserMerchantType type) {
		Check.notEmpty(merchantId, "商户id不能为空");
		Check.notEmpty(account, "商户帐号不能为空");
		Check.notEmpty(busdId, "商圈id不能为空");
		Check.notEmpty(password, SystemCode.PASSWORD_NOTNULL.getMessage());

		com.dragon.modules.yuegou.model.system.User sysUser = sysUserService.getMerchantUserByMobile(account);
		if (sysUser != null) {
			throw new DragonException(MerchantCode.MOBILE_REGISTERED.getCode(),String.format(MerchantCode.MOBILE_REGISTERED.getMessage(),sysUser.getNickName()));
		}
		sysUser = sysUserService.createAccount(account, account, username, password);

		User user = new User();
		user.setId(sysUser.getId());
		user.setMerchantId(merchantId);
		user.setBusdId(busdId);
		user.setUserId(sysUser.getId());
		user.setMerchantType(type);
		user.setDel(false);
		Long count = 0l;
		if (org.apache.commons.lang3.StringUtils.isNotEmpty(sysUser.getId())){
			QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq(UserEntity.COL_ID,sysUser.getId());
			count = baseMapper.selectCount(queryWrapper);
		}
		if (count > 0){
			updateById(user);
		}else {
			save(user);
		}
	}

	@Override
	public User loginByMobile(String mobile, String password) {
		Check.notNull(mobile, SystemCode.MOBILE_NOTNULL.getMessage());
		Check.notNull(password, SystemCode.PASSWORD_NOTNULL.getMessage());
		com.dragon.modules.yuegou.model.system.User sysUser = sysUserService.getMerchantUserByMobile(mobile);
		sysUserService.login(sysUser, password);
		User user = getBySysUserId(sysUser.getId());
		user.setSysUser(sysUser);
		return user;
	}
	
	@Override
	public User loginByMobile(String mobile) {
		Check.notNull(mobile, SystemCode.MOBILE_NOTNULL.getMessage());
		com.dragon.modules.yuegou.model.system.User sysUser = sysUserService.getMerchantUserByMobile(mobile);
		if(null == sysUser) {
			return null;
		}
		User user = getBySysUserId(sysUser.getId());
		user.setSysUser(sysUser);
		return user;
	}

	@Override
	public User loginByOpenId(String openid, String appId) {
		Check.notNull(openid, "openid不能为空");
		Check.notNull(appId, "appId不能为空");
		WxOpenidRef openidRef = wxOpenidRefService.getByOpenId(openid, appId);
		if (openidRef == null) {
			throw new DragonException(MerchantCode.OPENID_NOT_FIND);
		}
		com.dragon.modules.yuegou.entity.system.UserEntity sysUser = sysUserService.getById(openidRef.getUserId());
		if (sysUser == null) {
			throw new DragonException(MerchantCode.OPENID_NOT_FIND_MERCHAN_USER);
		}
		UserQuery query = new UserQuery();
		query.setUserId(openidRef.getUserId());
		query.setDel(false);
		UserEntity entity = this.getOne(query.toQueryWrapper());
		if (entity == null) {
			throw new DragonException(MerchantCode.APPID_USER_IS_NOT_MERCHANT);
		}
		User user = new User(entity);
		user.setSysUser(new com.dragon.modules.yuegou.model.system.User(sysUser));
		return user;
	}

	@Override
	public User loginByUsername(String username, String password) {
		Check.notNull(username, "用户名不能为空");
		Check.notNull(password, SystemCode.PASSWORD_NOTNULL.getMessage());
		com.dragon.modules.yuegou.model.system.User sysUser = sysUserService.getMerchantUserByUsername(username);
		sysUserService.login(sysUser, password);
		User user = getBySysUserId(sysUser.getId());
		user.setSysUser(sysUser);
		return user;
	}

	@Override
	public User getBySysUserId(String userId) {
		UserQuery userQuery = new UserQuery();
		userQuery.setDel(false);
		userQuery.setUserId(userId);
		List<UserEntity> list = this.list(userQuery.toQueryWrapper());
		if (CollectionUtils.isEmpty(list)) {
			throw new DragonException(MerchantCode.MERCHANT_NOT_EXIST);
		}
		return new User(list.get(0));
	}

	@Override
	public List<User> busdUserList(String busdId){
		return baseMapper.busdUserList(busdId);
	}

}